﻿using CF3;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System.Text;
using System.Threading.Tasks;

namespace {{cookiecutter.project_name}}
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddFrameworkServices(Configuration);
            services.AddIoCService();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseFramework();
            app.UseExceptionHandler(builder => builder.Run(async context => await ErrorEvent(context)));
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseSession();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        #region 当MVC拦截不到，由中间件处理全局未处理的异常
        /// <summary>
        /// 当MVC拦截不到，由中间件处理全局未处理的异常
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private Task ErrorEvent(HttpContext context)
        {
            var feature = context.Features.Get<IExceptionHandlerFeature>();
            var error = feature?.Error;
            LogHelper.WriteError<Startup>(error);
            context.Response.Clear();
            context.Response.ContentType = "application/json; charset=utf-8";
            var result = CallResult.Create(CallResultCode.Error, "系统异常：" + error.Message);
            return context.Response.WriteAsync(JsonConvert.SerializeObject(result));
        }
        #endregion
    }
}
